/**
 * 平台选择弹窗组件
 * 用于选择已授权的平台进行文档发布
 */
class PlatformSelectModal {
    constructor() {
        // 初始化弹窗
        this.init();
    }

    /**
     * 初始化弹窗组件
     */
    init() {
        // 创建弹窗HTML结构
        this.createModalHTML();
        
        // 获取弹窗元素引用
        this.platformModal = $('#platformSelectModal');
        this.platformModalTitle = $('#platformModalTitle');
        this.platformModalContent = $('#platformModalContent');
        this.platformList = $('#platformList');
        this.closePlatformModal = $('#closePlatformModal');
        this.cancelPlatformSelection = $('#cancelPlatformSelection');
        this.confirmPlatformSelection = $('#confirmPlatformSelection');
        
        // 存储当前选择的文档和平台
        this.currentPublishData = {
            documents: [],
            selectedPlatforms: [],
            isBatch: false
        };
        
        // 初始化事件监听
        this.initEvents();
    }
    
    /**
     * 从账号管理接口获取已授权的平台数据
     */
    async fetchAuthorizedPlatforms() {
        try {
            const response = await fetch('/api/accounts', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'same-origin'
            });
            
            // 处理未授权错误
            if (response.status === 401) {
                alert('请先登录以查看已授权的平台');
                return [];
            }
            
            const data = await response.json();
            
            // 如果成功获取到账号数据，返回格式化的平台列表
            if (response.ok && data?.data && Array.isArray(data.data)) {
                return data.data.map(account => {
                    // 同时支持account_type和accountType字段
                    const accountType = account.account_type || account.accountType;
                    const expireTime = account.expire_time || account.expiresAt;
                    const typeInfo = this.getAccountTypeInfo(accountType);
                    return {
                        id: account.account_id, // 使用账号ID作为唯一标识
                        name: account.accountName || '未命名账号',
                        type: accountType,
                        typeInfo: typeInfo,
                        isExpired: expireTime ? new Date(expireTime) < new Date() : false
                    };
                });
            }
            return [];
        } catch (error) {
            console.error('获取授权平台失败:', error);
            alert('获取授权平台列表失败，请稍后重试');
            return [];
        }
    }
    
    /**
     * 根据数据库中的账号类型，获取对应的图标和颜色
     * 与account-management.js保持一致的映射逻辑
     */
    getAccountTypeInfo(type) {
        const typeMap = {
            1: { icon: 'fa-weixin', color: 'bg-green-100 text-green-600', name: '微信' },
            2: { icon: 'fa-music', color: 'bg-red-100 text-red-600', name: '抖音' },
            3: { icon: 'fa-user', color: 'bg-blue-100 text-blue-600', name: '系统账号' },
            4: { icon: 'fa-envelope-o', color: 'bg-yellow-100 text-yellow-600', name: '邮箱' }
        };
        return typeMap[type] || { icon: 'fa-user-circle-o', color: 'bg-gray-100 text-gray-600', name: '其他' };
    }

    /**
     * 创建弹窗HTML结构
     */
    createModalHTML() {
        // 平台选择弹窗HTML结构
        const platformModalHTML = `
            <div id="platformSelectModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
                <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
                    <div class="flex justify-between items-center mb-4">
                        <h3 id="platformModalTitle" class="text-xl font-bold text-gray-800">选择发布平台</h3>
                        <button id="closePlatformModal" class="text-gray-500 hover:text-gray-700 focus:outline-none">
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        </button>
                    </div>
                    <div class="mb-4">
                        <p id="platformModalContent" class="text-gray-600"></p>
                    </div>
                    <div class="mb-4">
                        <div id="platformList" class="space-y-2">
                            <!-- 平台选项将动态添加 -->
                        </div>
                    </div>
                    <div class="flex justify-end space-x-2">
                        <button id="cancelPlatformSelection" class="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300">取消</button>
                        <button id="confirmPlatformSelection" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">确定</button>
                    </div>
                </div>
            </div>
        `;
        
        // 添加弹窗到页面
        $('body').append(platformModalHTML);
    }

    /**
     * 初始化事件监听
     */
    initEvents() {
        // 关闭按钮事件
        this.closePlatformModal.on('click', () => this.hideModal());
        
        // 取消按钮事件
        this.cancelPlatformSelection.on('click', () => this.hideModal());
        
        // 确认按钮事件
        this.confirmPlatformSelection.on('click', () => this.handleConfirm());
        
        // 点击弹窗外部关闭
        this.platformModal.on('click', (event) => {
            if (event.target === this.platformModal[0]) {
                this.hideModal();
            }
        });
    }

    /**
     * 显示平台选择弹窗
     * @param {Array} documents - 要发布的文档数组
     * @param {boolean} isBatch - 是否为批量发布
     */
    async showModal(documents, isBatch = false) {
        this.currentPublishData.documents = documents;
        this.currentPublishData.isBatch = isBatch;
        this.currentPublishData.selectedPlatforms = [];
        
        // 设置弹窗标题和内容
        if (isBatch) {
            this.platformModalTitle.text('批量选择发布平台');
            this.platformModalContent.text(`您选择了 ${documents.length} 个文档，点击选择要发布的平台：`);
        } else {
            this.platformModalTitle.text('选择发布平台');
            this.platformModalContent.text(`您将要发布文档 "${documents[0].title}"，点击选择要发布的平台：`);
        }
        
        // 清空平台列表并显示加载状态
        this.platformList.empty();
        this.platformList.append('<div class="text-center py-8 text-gray-500">正在加载已授权平台...</div>');
        
        // 显示弹窗
        this.platformModal.removeClass('hidden');
        
        // 从账号管理获取已授权平台
        const authorizedPlatforms = await this.fetchAuthorizedPlatforms();
        
        // 清空并添加平台选项
        this.platformList.empty();
        
        if (authorizedPlatforms.length === 0) {
            this.platformList.append('<div class="text-center py-8 text-gray-500">暂无已授权的平台，请先在账号管理中添加</div>');
            return;
        }
        
        authorizedPlatforms.forEach(platform => {
            // 使用Font Awesome图标显示平台类型，与账号管理一致
            const platformItem = $('<div class="flex items-center space-x-3 p-3 border rounded-lg cursor-pointer hover:bg-gray-50 transition-all duration-200 flex-wrap">')
                .append($('<input type="checkbox" class="platform-checkbox w-5 h-5 accent-blue-500" value="' + platform.id + '" ' + (platform.isExpired ? 'disabled' : '') + '>'))
                .append($('<div class="w-10 h-10 ' + platform.typeInfo.color.split(' ')[0] + ' rounded-full flex items-center justify-center">')
                    .append($('<i class="fa ' + platform.typeInfo.icon + ' text-xl ' + platform.typeInfo.color.split(' ')[1] + '"></i>')))
                .append($('<div class="flex-1">')
                    .append($('<label class="cursor-pointer font-medium text-gray-700">' + platform.name + '</label>'))
                    .append($('<span class="text-xs text-gray-500">' + platform.typeInfo.name + '</span>')));
            
            if (platform.isExpired) {
                platformItem.append($('<span class="bg-red-100 text-red-800 text-xs px-2 py-1 rounded-full">已过期</span>'));
            }
            
            platformItem.on('click', (event) => {
                if (event.target.tagName !== 'INPUT' && !platform.isExpired) {
                    const checkbox = $(event.currentTarget).find('input');
                    checkbox.prop('checked', !checkbox.prop('checked'));
                    this.updateSelectedPlatforms();
                }
            });
            
            platformItem.find('input').on('change', () => this.updateSelectedPlatforms());
            this.platformList.append(platformItem);
        });
    }

    /**
     * 隐藏弹窗
     */
    hideModal() {
        this.platformModal.addClass('hidden');
    }

    /**
     * 更新选中的平台
     */
    updateSelectedPlatforms() {
        this.currentPublishData.selectedPlatforms = this.platformList.find('input:checked').map(function() {
            return $(this).val();
        }).get();
    }

    /**
     * 处理确认选择
     */
    async handleConfirm() {
        if (this.currentPublishData.selectedPlatforms.length === 0) {
            alert('请至少选择一个发布平台');
            return;
        }
        
        // 重新获取平台列表以获取最新信息
        const authorizedPlatforms = await this.fetchAuthorizedPlatforms();
        
        const selectedPlatformNames = this.currentPublishData.selectedPlatforms.map(platformId => {
            const platform = authorizedPlatforms.find(p => p.id === platformId);
            return platform ? platform.name : platformId;
        }).join(', ');
        
        // 显示加载中状态
        const originalButtonText = this.confirmPlatformSelection.text();
        this.confirmPlatformSelection.prop('disabled', true);
        this.confirmPlatformSelection.text('发布中...');
        
        // 构建发布数据
        const publishData = {
            documents: this.currentPublishData.documents,
            platforms: this.currentPublishData.selectedPlatforms,
            isBatch: this.currentPublishData.isBatch
        };
        
        console.log('准备发布内容到平台:', publishData);
        
        try {
            // 调用后端发布接口
            const response = await fetch('/api/publish', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'same-origin',
                body: JSON.stringify(publishData)
            });
            
            // 确保响应被正确处理
            if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
            }
            
            let data;
            try {
                data = await response.json();
            } catch (jsonError) {
                console.error('解析响应JSON失败:', jsonError);
                data = { success: false, message: '响应格式错误' };
            }
            
            if (data.success) {
                if (this.currentPublishData.isBatch) {
                    alert(`批量发布 ${this.currentPublishData.documents.length} 个文档到以下平台成功：${selectedPlatformNames}\n${data.platformResponse || ''}`);
                } else {
                    alert(`发布文档 "${this.currentPublishData.documents[0].title}" 到以下平台成功：${selectedPlatformNames}\n${data.platformResponse || ''}`);
                }
            } else {
                alert('发布失败: ' + (data.message || '未知错误'));
            }
        } catch (error) {
            console.error('发布请求失败:', error);
            alert('发布请求失败: ' + error.message);
        } finally {
            // 恢复按钮状态
            this.confirmPlatformSelection.prop('disabled', false);
            this.confirmPlatformSelection.text(originalButtonText);
            this.hideModal();
        }
    }
}

// 创建全局实例
let platformSelectModal;

// 初始化函数，在页面加载完成后调用
function initPlatformSelectModal() {
    if (!platformSelectModal) {
        platformSelectModal = new PlatformSelectModal();
    }
    return platformSelectModal;
}

// 导出初始化函数
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = { initPlatformSelectModal };
}